package com.example.yilanchatserver.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.PropertySource;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @program: I18nConfig
 * @description:
 * @author: bob
 * @create: 3/23/21 5:34 PM
 */
@Slf4j
@PropertySource(value = {"classpath:i18n/messages*.properties"})
public class I18nConfig {

    /**
     * 将国际化信息存放在一个map中
     */
    private static final Map<String, ResourceBundle> MESSAGES = new HashMap<String, ResourceBundle>();

    /**
     * 获取国际化信息
     */
    public static String getMessage(HttpServletRequest request, String key, Object... params) {
        //获取语言，这个语言是从header中的Accept-Language中获取的，
        //会根据Accept-Language的值生成符合规则的locale，如zh、pt、en等
        try {
            String lauage = request.getHeader("Accept-Language");
            Locale locale = null;
            if (lauage == null) {
                locale = request.getLocale();
            } else if ("en".equals(lauage)) {
                locale = Locale.ENGLISH;
            } else if ("zh".equals(lauage)) {
                locale = Locale.CHINA;
            }
            //其余的不正确的默认就是本地的语言
            else {
                locale = request.getLocale();
            }
            ResourceBundle message = MESSAGES.get(locale.getLanguage());
            if (message == null) {
                synchronized (MESSAGES) {
                    //在这里读取配置信息
                    message = MESSAGES.get(locale.getLanguage());
                    if (message == null) {
                        //注1
                        message = ResourceBundle.getBundle("i18n/messages", locale);
                        MESSAGES.put(locale.getLanguage(), message);
                    }
                }
            }
            //此处获取并返回message
            if (params != null) {
                return String.format(message.getString(key), params);
            }
            return message.getString(key);
        } catch (Exception e) {
            log.error(e.getMessage());
            return "server error";
        }
    }

    /**
     * 清除国际化信息
     */
    public static void flushMessage() {
        MESSAGES.clear();
    }
}
